<template>
  <v-layout type="main">
    <!-- <p class="page-title">模型训练</p> -->

    <el-steps :active="active" v-if="operator == 1 || operator == 2" simple class="my-steps">
      <el-step title="基本信息" icon="el-icon-edit"></el-step>
      <el-step title="上传文件" icon="el-icon-upload"></el-step>
      <el-step title="完成" icon="el-icon-picture"></el-step>
    </el-steps>
    <div class="detail-layout">
      <br/>
      <el-form class="form myself-form alick-add-form" ref="form" :model="addForm" :rules="submitRules"
               label-width="120px">
        <div v-if="active == 1">
          <div v-if="operator == 1">
            <h3 class="add-alike-title">基本信息</h3>
            <el-form-item label="名称" prop="name">
              <el-input type="text" v-model="addForm.name"/>
            </el-form-item>
            <el-form-item label="描述" prop="desc">
              <el-input type="textarea" :rows="3" v-model="addForm.desc"/>
            </el-form-item>
          </div>
          <div v-if="operator == 2">
            <el-form-item label="名称" prop="model_name">
              {{ addForm.name }}
            </el-form-item>
          </div>
          <div v-if="operator == 3">
            <div v-if="task_id == null">
              <el-form-item label="名称" prop="name">
                <el-input type="text" v-model="addForm.name"/>
              </el-form-item>
              <el-form-item label="描述" prop="desc">
                <el-input type="textarea" :rows="6" v-model="addForm.desc"/>
              </el-form-item>
            </div>
            <div v-else>
              <el-form-item label="名称" prop="model_name">
                {{ addForm.name }}
                <a href="javascript:;" @click="preAddTask">新增训练任务</a>
              </el-form-item>
            </div>
          </div>


          <h3 class="add-alike-title">版本信息</h3>
          <el-form-item label="版本" prop="version">
            <el-input type="text" v-model="addForm.version" readonly/>
          </el-form-item>
          <el-form-item label="提交信息" prop="commit_msg">
            <el-input type="textarea" :rows="3" v-model="addForm.commit_msg"/>
          </el-form-item>
          <h3 class="add-alike-title">仿真环境</h3>
          <el-form-item label="仿真环境">
            <el-select v-model="simulation.image_id" @change="changeSimulationImage()"
                       prop="simulation_image_id" class="full-extent-select">
              <el-option v-for="item in simulationImageOptions" :value="item.id" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="想定">
            <el-select v-model="scenario" @change="changeScenario(scenario)" prop="scenario_id"
                       class="full-extent-select">
              <el-option v-for="item in scenarioOptions" :value="item" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数量">
            <el-input-number v-model="simulation.pod_num"></el-input-number>
          </el-form-item>
          <!-- <el-form-item label="启动命令行" prop="command">
            <el-input type="textarea" @input="onInput" :rows="2" v-model="simulation.command" />
          </el-form-item> -->
          <h3 class="add-alike-title">开发环境</h3>
          <div class="node-module">
            <h3 class="node-module-title">主节点</h3>
            <el-form-item label="环境" prop="mainNodeImageId">
              <el-cascader v-model="mainNode.image_group" :options="imageOptions" :show-all-levels="false"
                           class="full-extent-select"></el-cascader>
            </el-form-item>
            <el-form-item label="资源组">
              <el-select v-model="mainNode.product_id" class="full-extent-select">
                <el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="启动命令行" prop="command">
              <el-input type="textarea" :rows="2" v-model="mainNode.command" required />
            </el-form-item>
            <div class="right-btn-box" v-if="slaveNodeList.length == 0">
              <span class="outin-handle">
                <a href="javascript:;" @click="addSlaveNode()">增加</a>
              </span>
            </div>
          </div>
          <div v-for="(tag, i) in slaveNodeList" :key="i">
            <div class="node-module">
              <h3 class="node-module-title">从节点</h3>
              <el-form-item label="环境" prop="slaveImage">
                <el-cascader v-model="tag.image_group" :options="imageOptions" :show-all-levels="false"
                             class="full-extent-select"></el-cascader>
              </el-form-item>
              <el-form-item label="资源组">
                <el-select v-model="tag.product_id" class="full-extent-select">
                  <el-option v-for="item in productOptions" :value="item.id" :label="item.name" :key="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="数量">
                <el-input-number v-model="tag.pod_num"></el-input-number>
              </el-form-item>
              <el-form-item label="启动命令行" prop="command">
                <el-input type="textarea" :rows="2" v-model="tag.command"/>
              </el-form-item>
              <!-- <a href="javascript:;" @click="delSlaveNode(i)">删除</a> -->
              <div class="right-btn-box">
                <span class="outin-handle">
                  <a href="javascript:;" @click="delSlaveNode(i)">删除</a>
                  <a href="javascript:;" @click="addSlaveNode()" v-if="i == slaveNodeList.length - 1">增加</a>
                </span>
              </div>
            </div>
          </div>
          <!-- <a href="javascript:;" @click="addSlaveNode()">增加</a> -->
          <el-form-item label="超参" prop="param">
            <div class="outin-box" v-for="(e, i) in parameter_list" :key="e.id">
              <div class="port-lis">
                <span class="outin-input-name-title">名称</span>
                <el-input type="text" v-model="e.name" class="port-el-input"/>
                <!-- <span class="outin-input-name-title">=</span> -->
                <span class="outin-input-name-title">值</span>
                <el-input type="text" v-model="e.value" class="port-el-input"/>
              </div>
              <span class="outin-handle">
                <a href="javascript:;" @click="addParam(i)" v-if="i == parameter_list.length - 1">增加</a>
                <span v-else class="slot-btn"></span>
                <a href="javascript:;" @click="delParam(i)" v-if="parameter_list.length > 1">删除</a>
              </span>
            </div>
          </el-form-item>
        </div>
        <div v-if="active == 2">
          <!-- <p class="uploader-hint">文件会上传到/workspace目录下，会持久保存，重启容器时不会丢失</p> -->
          <el-form-item label="上传文件 " prop=" ">
            <wrapUploader @succeedOver="succeedOver" type="workspace" :biz_id="taskVersion.id"/>
          </el-form-item>
        </div>
        <div v-show="active == 3">
          <p class="succeed-hint">创建成功</p>
          <div class="succeed-btn">
            <a href="javascript:;" class="start" @click="startTask">启动</a>
            <a href="javascript:;" class="go" @click="toDetail">立即前往</a>
          </div>
        </div>
        <el-form-item label=" ">
          
          <el-button class="none-type" type="primary" @click="nextSubmmit"
                     v-if="operator == 1 && active == 1">下一步
          </el-button>
          <el-button class="none-type" type="primary" @click="submmit"
                     v-if="operator == 2 && active == 1">下一步
          </el-button>
          <el-button class="none-type" type="primary" @click="fileSubmmit"
                     v-if="(operator == 1 || operator == 2) && active == 2">确定
          </el-button>
          <el-button class="none-type" type="primary" @click="submmit"
                     v-if="operator == 3 && active == 1">确定
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </v-layout>
</template>

<script>
import {addGameTaskVersion, getAllGameTaskVersions, getGameTaskVersionDetail} from '@/api/gameTask'
import {addGameTask, getGameTaskDetail} from '@/api/gameTask'
import {getAllProducts} from '@/api/product'
import {getAllImages, getImageDetail, getAllImageGroups} from '@/api/image'
import {getGameExperimentDetail} from '@/api/gameExperiment'
import {mainImageRule, mainProductRule} from '@/utils/rule'
import {getAllScenarios} from '@/api/scenario'

export default {
  data() {
    return {
      operator: 1, //1新增  2新增版本 3复制
      active: 1,
      addForm: {status: 0},
      taskVersion: {},
      port_list: [],
      parameter_list: [{}],
      mainNode: {visibility: '2', engine: '0', imageOptions: [], type: 1, pod_num: 1},
      slaveNodeList: [],
      simulation_deduction_list: [],
      simulation_port_list: [],
      submitRules: {
        name: [
          {required: true, message: "该项为必填项"},
          {required: true, min: 1, max: 40, message: "长度在1到40个字符"},
        ],
        desc: [
          {required: true, message: "该项为必填项"},
          {required: true, min: 1, max: 200, message: "长度在1到40个字符"},
        ],
        main_image_id: [
          {required: true, message: "该项为必填项"},
        ],
        main_product: [
          {required: true, message: "该项为必填项"},
        ],
        mainNodeImageId: [
          {required: true, validator: mainImageRule.bind(this, this), trigger: 'change'}
        ],
        mainProduct: [
          {required: true, validator: mainProductRule.bind(this, this), trigger: 'change'}
        ],
      },
      simulation: {pod_num: 1},
      imageOptions: [],
      productOptions: [],
      experiment_id: this.$route.query.experiment_id, //模型开发的ID
      task_id: this.$route.query.task_id, //模型开发的ID
      scenarioOptions: [],
      simulationImageOptions: [],
      modelOptions: [],
      modelVersionOptions: [],
      scenario: null,
    };
  },
  components: {},
  async created() {
    this.getData()
    this.getSimulationImage()
    this.getAllImageGroups()
  },
  watch: {
    'parameter_list': {
      handler: 'syncKeyWithValue',
      deep: true
    }
  },
  methods: {
    async setAddForm() {
      console.log("begin add ")
      console.log('simulation', this.simulation)
      this.addForm.type = '1'
      this.addForm.node_group_list = []
      this.addForm.simulation_port_list = this.simulation_port_list
      this.addForm.simulation_deduction_list = this.simulation_deduction_list
      this.addForm.simulation_node_group = this.simulation
      this.addForm.simulation_node_group.image_id = this.simulation.image_id
      this.addForm.scenario_id = this.scenario.id
      console.log('scenario_id', this.addForm.scenario_id)
      console.log('simulation_deduction_list', this.simulation_deduction_list)
      this.addForm.node_group_list = []
      this.mainNode.type = 1
      this.mainNode.image_id = this.mainNode.image_group[2]
      this.addForm.node_group_list.push(this.mainNode)
      for (let i = 0; i < this.slaveNodeList.length; i++) {
        this.slaveNodeList[i].type = 2
        this.slaveNodeList[i].image_id = this.slaveNodeList[i].image_group[2]
        this.addForm.node_group_list.push(this.slaveNodeList[i])
      }
      this.addForm.parameter_list = []

      for (let i = 0; i < this.parameter_list.length; i++) {
        if (this.parameter_list[i].name != null && this.parameter_list[i].name.length > 0) {
          if (this.parameter_list[i].name == null || this.parameter_list[i].value == null) {
            alert('参数不能为空')
          } else {
            this.addForm.parameter_list.push(this.parameter_list[i])
          }
        }
      }

    },
    async getAddForm(data) {
      console.log("getAddForm")
      this.addForm = data
      this.simulation = data.simulation_node_group
      await this.changeSimulationImage()
      this.scenario = data.scenario
      await this.changeScenario(this.scenario)
      this.simulation_deduction_list = data.simulation_deduction_list
      // this.simulation = data
      this.parameter_list = []
      this.slaveNodeList = []
      for (let node of data.node_group_list) {
        if (node.type == 1) {
          this.mainNode = node
          let res = await getImageDetail({id: this.mainNode.image_id})
          let mainImage = res.data
          this.mainNode.image_group = [mainImage.visibility.toString(), mainImage.engine.toString(), mainImage.id]
        } else {
          let res = await getImageDetail({id: node.image_id})
          let slaveImage = res.data
          let slaveNode = node
          slaveNode.image_group = [slaveImage.visibility.toString(), slaveImage.engine.toString(), slaveImage.id]
          this.slaveNodeList.push(slaveNode)
        }
      }
      if (data.parameter_list) {
        this.parameter_list = data.parameter_list
      }
      if (this.parameter_list.length == 0) {
        this.parameter_list.push({})
      }
    },
    preAddTask() {
      this.task_id = null
      this.addForm.version = "v1"
    },

    async getData() {
      if (this.task_id == null && this.experiment_id == null) {
        this.operator = 1
        this.addForm.version = "v1"
      }
      if (this.task_id && this.experiment_id == null) {
        this.operator = 2
        let res = await getAllGameTaskVersions({gameTaskId: this.task_id, type: 1})
        if (res && res.data) {
          let ve = res.data[0]
          let ret = await getGameTaskVersionDetail({id: ve.id})
          let data = ret.data
          this.getAddForm(data)
        }
        let ret = await getGameTaskDetail({id: this.task_id})
        let data = ret.data
        this.addForm.name = data.name
        this.addForm.version = "v" + (data.version_index + 1)
      }
      if (this.experiment_id) {
        this.operator = 3
        let res = await getGameExperimentDetail({id: this.experiment_id})
        let data = res.data
        this.getAddForm(data)
        this.addForm.copy_from = this.experiment_id
        this.addForm.version = "v1"
        if (this.task_id) {
          let res = await getGameTaskDetail({id: this.task_id})
          let data = res.data
          this.addForm.name = data.name
          this.addForm.version = "v" + (data.version_index + 1)
          this.addForm.game_task_id = this.task_id
          console.log("this.addForm.game_task_id", this.addForm.game_task_id)
        }
      }
      this.getProductList()
    },
    async getAllImageGroups() {
      let res = await getAllImageGroups()
      this.imageOptions = res.data
    },
    async getProductList() {
      let res = await getAllProducts()
      this.productOptions = res.data
    },
    async getSimulationImage() {
      let ret = await getAllImages({visibility: '1', type: 3})
      this.simulationImageOptions = ret.data
    },

    async changeSimulationImage() {
      if (this.simulation) {
        let ret = await getAllScenarios({imageId: this.simulation.image_id})
        console.log('ret', ret.data)
        this.scenarioOptions = ret.data
        let simulationCommand = this.simulation.command;
        if (this.simulation.image_id) {
          let res = await getImageDetail({id: this.simulation.image_id})
          let image = res.data
          if (res && res.data) {
            this.simulation_port_list = image.port_list
            this.simulation.product_id = image.product_id
            this.simulation.command = image.command
          }
        }
        if (simulationCommand != null) {
          this.simulation.command = simulationCommand
        }
      }
    },
    async changeScenario(scenario) {
      console.log("changeScenario", scenario)
    },
    onInput() {
      this.$forceUpdate();
    },
    syncKeyWithValue() {
      this.parameter_list.forEach(param => {
        param.key = param.value; // 同步 key 与 value
      });
    },
    addParam() {
      this.parameter_list.push({})
      this.syncKeyWithValue()
    },
    delParam(i) {
      this.parameter_list.splice(i, 1)
    },
    addSlaveNode() {
      this.slaveNodeList.push({pod_num: 1})
    },
    delSlaveNode(i) {
      this.slaveNodeList.splice(i, 1)
    },
    fileSubmmit() {
      this.active = 3
    },

    async submmit() {
      console.log("this.addForm.game_task_id", this.addForm.game_task_id)
      this.setAddForm()
      console.log("this.addForm.game_task_id", this.addForm.game_task_id)
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.task_id) {
            console.log("this.addForm.game_task_id", this.addForm.game_task_id)
            let ret = await addGameTaskVersion({...this.addForm})
            this.taskVersion = ret.data
          } else {
            let ret = await addGameTask({...this.addForm})
            this.task_id = ret.data.id
          }
        }
        if (this.operator == 2) {
          this.active = 2
        }
        if (this.operator == 3) {
          this.active = 3
        }
      })
      console.log("active", this.active)
    },

    startTask() {

    },
    toDetail() {
      console.log('addForm', this.addForm)
      let query = {
        id: this.task_id
      }
      this.$router.push({
        path: '/gameTask/code',
        query
      })
    },
    succeedOver(data) {
      console.log(data)
    },
    async getTaskVersions(task_id) {
      let ret = await getAllGameTaskVersions({taskId: task_id})
      if (ret.data.length > 0) {
        this.taskVersion = ret.data[0]
      }
    },
    nextSubmmit() {
      this.setAddForm()
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          //新增任务和版本
          console.log("addForm", this.addForm)
          let res = await addGameTask(this.addForm);
          this.addForm = res.data
          this.task_id = this.addForm.id
          let version_ret = await getAllGameTaskVersions({type: '1', model_id: this.model_id})
          this.versionOptions = version_ret.data
          if (this.versionOptions.length > 0) {
            this.taskVersion = this.versionOptions[0]
          }
          this.active = 2
        }
      })
    }
  },

}
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-add.less";
</style>
